package service.impl.v2;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.DelayQueue;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import dao.v2.ApplyReturnVOMapper;
import dao.v2.ConfigVOMapper;
import dao.v2.MemberCartVOMapper;
import dao.v2.OrderVOMapper;
import dao.v2.PayVOMapper;
import dao.v2.PromotionVOMapper;
import dao.v2.TimerVOMapper;
import factory.DistributionLock;
import factory.RedisDistributionLock;
import model.AddressVO;
import model.CompanyVO;
import model.GoodLimitVO;
import model.GoodStandardVO;
import model.LogOrder;
import model.MemberCartVO;
import model.MemberVO;
import model.OrderCaseVO;
import model.OrderGoodVO;
import model.OrderTimer;
import model.OrderVO;
import model.PromotionGoodVO;
import model.PromotionItemVO;
import model.PromotionVO;
import model.RefuseReasonVO;
import model.StandardVO;
import service.v2.CacheManagerService;
import service.v2.ConfigService;
import service.v2.GoodTempService;
import service.v2.MemberCartServise;
import service.v2.MemberService;
import service.v2.OrderCancelService;
import service.v2.OrderService;
import service.v2.PayService;
import service.v2.SplitService;
import service.v2.TimerService;
import service.v2.UorderService;
import util.MessageUtil;
import util.OssUtil;
import util.PropertieUtil;

@Service
public class OrderServiceImpl implements OrderService {
	
	@Autowired
	private SplitService splitService;
	@Autowired
	private PayService payService;
	
	@Autowired
	private OrderCancelService orderCancelService;
	
	@Autowired
	private TimerService timerService;
	
	@Autowired
	private OrderVOMapper dao;
	
	@Autowired
	private ApplyReturnVOMapper applyReturnVOMapper;
	
	@Autowired
	private MemberCartVOMapper memberCartVOMapper;
	
	@Autowired
	private TimerVOMapper timerVOMapper;
	
	@Autowired
	private GoodTempService goodTempService;
	
	@Autowired
	private PayVOMapper payVOMapper;
	
	@Autowired
	private ConfigVOMapper ConfigDao;
	
	@Autowired
	private UorderService uorderService;
	
	@Autowired
	private MemberCartServise memberCartServise;
	
	@Autowired
	private PromotionVOMapper promotionVOMapper;
	
	@Autowired
	private CacheManagerService cacheManagerService;
	
	@Autowired
	private ConfigService configService;
	
	@Autowired
	private MemberService memberService;
	
	@Autowired
	@Qualifier("lockRedisTemplate")
	private RedisTemplate<Object, Object> lockRedisTemplate;
	
	private static final int good_limit_count = 10;
	
	public List<OrderVO> getList(OrderVO orderVO) {
		return dao.getList(orderVO) ;
	}

	public int getStateNum(String member_id, int type) {
		return dao.getStateNum(member_id, type);
	}


	
	public List<OrderVO> getAllOrderListByMemberId(OrderVO OrderVo) {
		return dao.getAllOrderListByMemberId(OrderVo) ;
	}

	public int getTotal(OrderVO orderVO) {
		// TODO Auto-generated method stub
		return dao.getTotal(orderVO);
	}

	public OrderVO getOrderConfirm(String order_id) {
		// TODO Auto-generated method stub
		dao.delOrderTimerByorderId(order_id, "1");
		return dao.getOrderConfirm(order_id);
	}

	public OrderVO getUnPayCancel(String order_id) {
		// TODO Auto-generated method stub
		return dao.getUnPayCancel(order_id);
	}

	public OrderVO getOrderUnpaid(String order_id) {
		// TODO Auto-generated method stub
		return dao.getOrderUnpaid(order_id);
	}

	public OrderVO getOrderUnsend(String order_id) {
		// TODO Auto-generated method stub
		return dao.getOrderUnsend(order_id);
	}

	public OrderVO getOrderUnReceived(String order_id) {
		// TODO Auto-generated method stub
		return dao.getOrderUnReceived(order_id);
	}

	public OrderVO getOrderSuccess(String order_id) {
		// TODO Auto-generated method stub
		return dao.getOrderSuccess(order_id);
	}

	public boolean judgeState(String order_id, String order_state) {
		return dao.judgeState(order_id,order_state)==0?false:true;
	}

	public void updOrderUnpaidToCancel(String order_id,String member_id) {
		// TODO Auto-generated method stub
		// 修改库存
		List<OrderGoodVO> orderGoodList	= dao.getOrderGoodByOrderId(order_id);
		for (int i = 0; i < orderGoodList.size(); i++) {
			dao.updStandardNum(orderGoodList.get(i).getGood_standard_id(),orderGoodList.get(i).getNum());
		}
		LogOrder log_ord = new LogOrder();
		log_ord.setOrder_id(order_id);
		log_ord.setMember_id(member_id);
		log_ord.setRemark("【订单】申请取消订单");
		//log_ord.setType("7");
		dao.InsertLogOrder(log_ord);
		//删除定时器
		dao.delOrderTimerByorderId(order_id,"4");
		dao.updOrderUnpaidToCancel(order_id);
	}

	public OrderVO getOrderDealCancelOnMain(String order_id) {
		// TODO Auto-generated method stub
		return dao.getOrderDealCancelOnMain(order_id);
	}

	public void updOrderInsertLogOrder(String member_id,String order_id, String cancel_reason) {
		// TODO Auto-generated method stub
		OrderVO  ord = new OrderVO();
		ord.setId(order_id);
		ord.setState("8");
		ord.setRefund_reason(cancel_reason);
		dao.updOrder(ord);
		
		LogOrder log_ord = new LogOrder();
		log_ord.setOrder_id(order_id);
		log_ord.setMember_id(member_id);
		log_ord.setRemark("【订单】已提交申请，正在受理");
		log_ord.setType("7");
		dao.InsertLogOrder(log_ord);

	}

	public List<LogOrder> getOrderLogByOrderId(String order_id,String type) {
		// TODO Auto-generated method stub
		return dao.getOrderLogByOrderId(order_id,type);
	}

	public void cancelPaidCancel(String member_id, String order_id) {
		// TODO Auto-generated method stub
		//delte  log_order  by order_id 
		OrderVO  ord = new OrderVO();
		ord.setId(order_id);
		ord.setState("3");
		dao.updOrder(ord);
		dao.deleteLogOrderByOrderId(order_id);
		LogOrder log_ord = new LogOrder();
		log_ord.setOrder_id(order_id);
		log_ord.setMember_id(member_id);
		log_ord.setRemark("【订单】已撤销取消订单申请");
		log_ord.setType("8");
		dao.InsertLogOrder(log_ord);
	}

	public OrderVO getOrderPaidCancel(String order_id) {
		// TODO Auto-generated method stub
		return dao.getOrderPaidCancel(order_id);
	}

	public String getTotalPriceByOrderId(String order_id) {
		// TODO Auto-generated method stub
		
		return dao.getTotalPriceByOrderId(order_id);
	}

	public void updOrderPayMethod(OrderVO order) {
		// TODO Auto-generated method stub
		dao.updOrderPayMethod(order);
	}

	public List<RefuseReasonVO> getAllRefuseMsg(String refuseReasonPid) {
		// TODO Auto-generated method stub
		return dao.getAllRefuseMsg(refuseReasonPid);
	}

	public List<OrderVO> getAllOrderListByMemberIdTwoState(OrderVO OrderVo) {
		// TODO Auto-generated method stub
		return dao.getAllOrderListByMemberIdTwoState(OrderVo);
	}

	public int getTotalTwoState(OrderVO OrderVo) {
		// TODO Auto-generated method stub
		return dao.getTotalTwoState(OrderVo);
	}

	public OrderVO getOrderDetails(String order_id) {
		// TODO Auto-generated method stub
		return dao.getOrderDetails(order_id);
	}

	public void checkOrderTime(String member_id, String order_id) throws Exception {
		//付款时间
		List<OrderTimer> orderTimerlist = dao.getTimerOrder(member_id,order_id);
		for (int i = 0; i < orderTimerlist.size(); i++) {
			OrderVO order = dao.getOrderById(orderTimerlist.get(i).getOrder_id());
			//付款倒计时
			if(order.getState().equals("1")||order.getState().equals("2")){
				if(orderTimerlist.get(i).getType().equals("4")){
					//
					if(orderTimerlist.get(i).getOpen_yn().equals("Y")){
						//时间已过期
						if(orderTimerlist.get(i).getNew_time().equals("false")){
							
								//交易关闭
								int count = dao.updOrderState(orderTimerlist.get(i).getOrder_id(),"6","1");
								if(count>0){
									//删除计时器
									dao.delOrderTimer(orderTimerlist.get(i).getId());
									//返回库存
									List<OrderGoodVO> orderGoodList	= dao.getOrderGoodByOrderId(order_id);
									
									for (int j = 0; j < orderGoodList.size(); j++) {
										dao.updStandardNum(orderGoodList.get(j).getGood_standard_id(),orderGoodList.get(j).getNum());
									}
									
									if("0".equals(order.getTicket_status())){
										// 交易退款 price 购买钱数 buy_cash 购物专用金 二选一 pay_type(兑换券,订单表的pay_type)
										try {
											splitService.payBack(order.getId(), order.getPay_type(), member_id, null, null);
										} catch (Exception e) {
											// TODO Auto-generated catch block
											e.printStackTrace();
										}
									}
									
									else if("1".equals(order.getTicket_status())){
										
										try {
											splitService.payBackUseTicket(order.getId(),order.getPay_type(),order.getCreate_by(),null,null);
										} catch (Exception e) {
											// TODO Auto-generated catch block
											e.printStackTrace();
										}
									}
								}
								
								
						}
						//时间未过期
						else{
								dao.updOrderTimerTime(orderTimerlist.get(i).getId(),orderTimerlist.get(i).getNew_time());
					
						}
					}
					//上次操作 ： 点击付款 并没有付款  让 定时器 接着走
					else if(orderTimerlist.get(i).getOpen_yn().equals("N")){
						dao.updOrderTimerYn(orderTimerlist.get(i).getId(),"Y");
					}
					
				}
			}
			//判断收货时间
			else if(order.getState().equals("4")){
				if(orderTimerlist.get(i).getType().equals("1")){
					if(orderTimerlist.get(i).getOpen_yn().equals("Y")){
						
						if(orderTimerlist.get(i).getNew_time().equals("false")){
							//交易关闭
							int count = dao.updOrderStateAndRecieveTime(orderTimerlist.get(i).getOrder_id(),"5");
							if(count>0){
								//删除计时器
								dao.delOrderTimer(orderTimerlist.get(i).getId());
								
								/*if("0".equals(order.getTicket_status())){
									payVOMapper.addHistoryTotalTicket(member_id, order.getTotal_ticket());
								      //检查升级
									payVOMapper.checkAndUpdateMemberLevel(member_id);
								}*/
								
								if("0".equals(order.getTicket_status())){
									//判断订单是否退过
									int orderBackCount = dao.checkOrderBackState(order_id);
									if(orderBackCount==0){
										try {
											splitService.settleAward(order_id);
										} catch (Exception e) {
											// TODO Auto-generated catch block
											e.printStackTrace();
										}
									}
								}
								
								else if("1".equals(order.getTicket_status())){
									// 提货券售出日志状态更变结算
									splitService.updateTicketLogSellSuccess(order_id);
								}
							}
							
						}
						else{							
							dao.updOrderTimerTime(orderTimerlist.get(i).getId(),orderTimerlist.get(i).getNew_time());
						}
						
					}else if(orderTimerlist.get(i).getOpen_yn().equals("N")){
						dao.updOrderTimerYn(orderTimerlist.get(i).getId(),"N");
					}
				}
			}
			
			 
		}
		
	}

	public List<LogOrder> getCencalOrderLog(String order_id) {
		// TODO Auto-generated method stub
		return dao.getCencalOrderLog(order_id);
	}

	public void OrderDelete(String order_id) {
		// TODO Auto-generated method stub
		dao.OrderDelete(order_id);
	}

	/*public int updOrderState(String order_id, String state) {
		// TODO Auto-generated method stub
		return dao.updOrderState(order_id,state);
	}*/

	public String getTotalPriceByPayNo(String[] order_id_List,String member_id) {
		// TODO Auto-generated method stub
		return dao.getTotalPriceByPayNo(order_id_List,member_id);
	}
	
	public String getTotalTicketByPayNo(String[] order_id_List,String member_id) {
		// TODO Auto-generated method stub
		return dao.getTotalTicketByPayNo(order_id_List,member_id);
	}

	public int getOrderCount(String[] order_id_List, String member_id) {
		// TODO Auto-generated method stub
		return dao.getOrderCount(order_id_List,member_id);
	}

	public int stopOrderPayTimerByPayNo(String[] order_id_List) {
		return dao.stopOrderPayTimerByPayNo(order_id_List);
	}

	public OrderVO getOrderAddressByPayNo(String[] order_id_List) {
		// TODO Auto-generated method stub
		return dao.getOrderAddressByPayNo(order_id_List);
	}

	public void InsertLogOrder(LogOrder log) {
		// TODO Auto-generated method stub
		dao.InsertLogOrder(log);
	}

	public OrderVO getOrderById(String id) {
		// TODO Auto-generated method stub
		return dao.getOrderById(id);
	}

	public void updOrderStateAndRecieveTime(String member_id,String order_id, String state) {
		// TODO Auto-generated method stub
		/*OrderVO order = dao.getOrderById(order_id);
		if(order!=null){
			if("0".equals(order.getTicket_status())){
				payVOMapper.addHistoryTotalTicket(member_id, order.getTotal_ticket());
			      //检查升级
				payVOMapper.checkAndUpdateMemberLevel(member_id);
			}
		}*/
		//添加销量
		 List<OrderGoodVO> order_good = dao.getOrderGoodByOrderId(order_id);
		 for (int i = 0; i < order_good.size(); i++) {
			dao.updateStoreSellNum(order_good.get(i).getGood_id(),order_good.get(i).getNum());
		}
		//修改收货时间
		dao.updOrderStateAndRecieveTime(order_id,state);
		//确认收货删除定时器
		dao.delOrderTimerByorderId(order_id, "1");
	}

	public String getTotalTicketByOrderId(String order_id) {
		// TODO Auto-generated method stub
		return dao.getTotalTicketByOrderId(order_id);
	}

	public String getToTalStandardTicket(String order_id) {
		// TODO Auto-generated method stub
		return dao.getToTalStandardTicket(order_id);
	}

	public int checkOrderPayState(String[] order_id_List) {
		// TODO Auto-generated method stub
		return dao.checkOrderPayState(order_id_List);
	}

	public String getToTalpackageTicket(String package_id) {
		// TODO Auto-generated method stub
		return dao.getToTalpackageTicket(package_id);
	}

	public int checkOrderBackState(String order_id) {
		// TODO Auto-generated method stub
		return dao.checkOrderBackState(order_id);
	}

	public void updOrderTimer(String member_id, String order_id) throws Exception {
		// TODO Auto-generated method stub
		//查看所有定时器
		List<OrderTimer> orderTimerlist = dao.getTimerOrder(member_id,order_id);
		
		if(orderTimerlist!=null&&orderTimerlist.size()>0){
			
			String[] order_id_List = new  String[orderTimerlist.size()];
			for (int i = 0; i < orderTimerlist.size(); i++) {
				order_id_List[i]=orderTimerlist.get(i).getOrder_id();
			}
			
			List<OrderVO> orderList = dao.getSimpleOrderByIdList(order_id_List);
			
			for (int i = 0; i < orderTimerlist.size(); i++) {
				
				for (int j = 0; j < orderList.size(); j++) {
					String order_timer_id = orderTimerlist.get(i).getId();
					if(orderTimerlist.get(i).getOrder_id().equals(orderList.get(j).getId())){
						OrderVO order = orderList.get(j);
						order_id = order.getId();
						if(order.getState().equals("1")||order.getState().equals("2")){
							if(orderTimerlist.get(i).getType().equals("4")){
								if(orderTimerlist.get(i).getOpen_yn().equals("Y")){
									//一小时已过期还没有支付
									if(orderTimerlist.get(i).getNew_time().equals("false")){
										orderCancelService.OrderCalcelNoPay(order.getId(),orderTimerlist.get(i).getId(),order.getTicket_status(),order.getPay_type(),order.getCreate_by());
									}
								}
								//未付款状态定时器停, 重新走定时器
								else if(orderTimerlist.get(i).getOpen_yn().equals("N")){
									int count = dao.delOrderTimer(orderTimerlist.get(i).getId());
									if(count>0){
										OrderTimer orderTime = new OrderTimer();
										orderTime.setOrder_id(orderTimerlist.get(i).getOrder_id());
										orderTime.setOpen_yn("Y");
										orderTime.setType("4");
										orderTime.setTime(orderTimerlist.get(i).getTime());
										memberCartVOMapper.addOrderTimer(orderTime);
										//timerService.orderPayTimer(orderTime.getId(), order.getId(), "", "0", pay_timer, "4");
										final String order_time_idt = orderTime.getId();
										final String order_idt = order.getId();
										final String pay_timert = orderTimerlist.get(i).getTime();
										
										 Thread t = new Thread(new Runnable(){  
									            public void run(){  
									            	timerService.orderPayTimer(order_time_idt, order_idt, "", "0", pay_timert, "4");
									            }
									      });  
									       t.start(); 
									}
								}
							}
						}
						//7天到时间确认收货
						else if(order.getState().equals("4")&&orderTimerlist.get(i).getType().equals("1")&&orderTimerlist.get(i).getOpen_yn().equals("Y")&&orderTimerlist.get(i).getNew_time().equals("false")){

								orderCancelService.confirmRecieve(orderTimerlist.get(i).getOrder_id(), orderTimerlist.get(i).getId(), order.getTicket_status(), order.getOrder_type());
						//14天未收到退货商品
						}else if(order.getState().equals("7")&&orderTimerlist.get(i).getType().equals("2")&&orderTimerlist.get(i).getOpen_yn().equals("Y")&&orderTimerlist.get(i).getNew_time().equals("false")){
								orderCancelService.neverRecieve14Days(order_id,orderTimerlist.get(i).getOrder_back_id(),order.getCreate_by(),orderTimerlist.get(i).getTime());

						}
					}
				}
			}
		}
	}

	public String getOrderBackSumPrice(String out_trade_no) {
		// TODO Auto-generated method stub
		return dao.getOrderBackSumPrice(out_trade_no);
	}

	public OrderTimer getReviceTimerByIdType(String order_id, String type) {
		// TODO Auto-generated method stub
		return dao.getReviceTimerByIdType(order_id,type);
	}

	public List<String> getRealPayOrderId(String[] order_id_list) {
		// TODO Auto-generated method stub
		return dao.getRealPayOrderId(order_id_list);
	}

	public StandardVO getStandardById(String standard_id) {
		// TODO Auto-generated method stub
		return dao.getStandardById(standard_id);
	}

	public String getOrderGoodName(String id) {
		return dao.getOrderGoodName(id);
	}
	
	public Map addPlaceOrder(MemberVO member, AddressVO addressVO, String cart_status, String cart_id,
			String ticket_status, String order_from, String standard_ids, String standard_nums,String country) {

		List<GoodStandardVO> standard_List = new ArrayList<GoodStandardVO>();		
		List<CompanyVO> companyList = new ArrayList<CompanyVO>();
		//直接下单
		if("0".equals(cart_status)){
			 standard_List = dao.getPlaceOrderStandardById(standard_ids,member.getLevel());
			 standard_List.get(0).setBuy_num(standard_nums);
			 companyList.add(new CompanyVO(standard_List.get(0).getCompany_id(),standard_List.get(0).getEnterprise_id()));
		}
		//购物车下单
		else if("1".equals(cart_status)){
			//查询购物车
			List<MemberCartVO> memberCartList = memberCartVOMapper.getMemberCardById(cart_id.split(","));
			//查询企业
			for (int i = 0; i < memberCartList.size(); i++) {
				boolean state = true;
				String company_id = memberCartList.get(i).getCompany_id();
				String enterprise_id =  memberCartList.get(i).getEnterprise_id();
				for (int j = 0; j < companyList.size(); j++) {
					if(enterprise_id.equals(companyList.get(j).getEnterprise_id())){
						state = false;
					}
				}
				if(state){
					companyList.add(new CompanyVO(company_id,enterprise_id));
				}
			}
			standard_List = dao.PlaceOrderStandardByCartId(cart_id.split(","),member.getLevel());
		}
		
		//生成订单
		Map map = dealOrder(companyList,standard_List,ticket_status,addressVO,order_from,member,country);
		if("200".equals(map.get("state").toString())){
			if("1".equals(cart_status)){
				//删除购物车
				memberCartVOMapper.deleteMemberCarById(cart_id.split(","), member.getId());
			}
			//分润(也不知道分啥。。就是分)
			dealBenifit(map,ticket_status,member);
		}
		
		return map;
	}
	
	
	private boolean checkGoodLimit(List<GoodStandardVO> standard_List){
		boolean good_limit_status = true;
		GoodLimitVO goodlimit = null;
		int limit_num = 0;
		int sale_num = 0;
		for (GoodStandardVO standard : standard_List){
			goodlimit = dao.getGoodLimitByGoodId(standard.getGood_id());
			if(goodlimit!=null&&"1".equals(goodlimit.getState())){
				limit_num = Integer.parseInt(goodlimit.getLimit_num()); 
				sale_num = Integer.parseInt(goodlimit.getSale_num());
				//要购买的大于剩下的
				if(Integer.parseInt(standard.getBuy_num())>limit_num-sale_num){
					if(Integer.parseInt(standard.getBuy_num())> good_limit_count ){
						good_limit_status = false;
						break;
					}
				}
			}
		}
		return good_limit_status;
	}
	
	private void dealGoodLimit(List<GoodStandardVO> standard_List){
		//操作
		GoodLimitVO goodlimit = null;
		for (GoodStandardVO standard : standard_List) {
			goodlimit = dao.getGoodLimitByGoodId(standard.getGood_id());
			if(goodlimit!=null&&"1".equals(goodlimit.getState())){
				dao.updLimitNum(standard.getGood_id(),standard.getBuy_num());
				int count = dao.updGoodLimitState(standard.getGood_id());
				if(count>0){
					try {
						promotionVOMapper.deleteCat_good_conn(standard.getGood_id(),PropertieUtil.loadPropertie("limited_ing"));
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				//清除缓存
				cacheManagerService.deleteSpecialListCache();
				cacheManagerService.deleteGoodDetailCache(CacheManagerServiceImpl.good_detail_key+standard.getGood_id());	
			}
		}
	}
	//按照供应商分单
	private Map dealOrder(List<CompanyVO> companyList,List<GoodStandardVO> standard_List,String ticket_status,AddressVO addressVO,String order_from,MemberVO member,String country)  {
		DistributionLock lock = new RedisDistributionLock(lockRedisTemplate,"dealOrder");
		lock.acquire();
		if(!checkGoodLimit(standard_List)){
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("state", "10909");
			map.put("msg", "限时购库存不足");
			map.put("result", "");
			map.put("remark", "");
			return map; 
		}
		dealGoodLimit(standard_List);	
		lock.release();
		//MEMBER_PRICE_TICKET
		String ticket_rule = ConfigDao.loadConfig("MEMBER_PRICE_TICKET");
		//MEMBER_PRICE_PERCENT
		String percent_rule = ConfigDao.loadConfig("MEMBER_PRICE_PERCENT");
		//String ticket_name = ConfigDao.loadConfig("TICKET_NAME");
		String ticket_name = ConfigDao.loadConfig("TICKET_NAME");
		//String pay_timer = ConfigDao.loadConfig("PAY_TIME");
		String pay_timer = ConfigDao.loadConfig("PAY_TIME");
		//可用的代金券
		int total_can_use_ticket = memberCartVOMapper.getCanUseTicket(member.getId());
		//会员折扣率
		double member_rate = dao.getDepositRate(member.getId());
		//会员优惠字符窜
		String level_str = dao.getLevelStrByMemberId(member.getId());
		//购物券量
		double Total_Ticket = 0;
		//所有订单价格综合
		double Total_Price = 0;
		//所有运费价格综合
		double Total_Freight = 0;
		//下架
		boolean shelves = true;
		//库存
		boolean stock  =  true;
		//订单异常(看折扣以后金额会不会出现负数)
		boolean order_price_state = true;
		//要生成的订单List
		List<OrderVO> orderList = new ArrayList<OrderVO>();
		breakfor:for (int i = 0; i < companyList.size(); i++) {
						 //企业
						 String enterprise_id = companyList.get(i).getEnterprise_id();
						 //要生成的订单
						 OrderVO order = new OrderVO();
						 List<OrderGoodVO> orderGoodList =  new ArrayList<OrderGoodVO>();
						 //是否是纯提货券订单
						 boolean order_ticket_status = true;
						 //订单总价(没包含运费)
						 double order_price = 0;
						 //订单总售价
						 double order_sell_price = 0;
						 //订单总提货券
						 double order_ticket = 0;
						 //订单总入会将
						 double order_award_join = 0;
						 //订单运费
						 double order_freight =0;
						 //会员优惠
						 double buy_sale = 0;
						 for (int j = 0; j < standard_List.size(); j++) {
							 //要生成的订单
							 OrderGoodVO orderGood =  new OrderGoodVO();
							 //商品规格
							 GoodStandardVO standardVO = standard_List.get(j);
							 //每个商品对应的企业
							 String good_enterprise_id = standard_List.get(j).getEnterprise_id();
							 //实际买的单格
							 double order_good_price = 0;
							 //实际用的兑换券
							 double order_good_ticket = 0; 
							 if(enterprise_id.equals(good_enterprise_id)){
								 	//商品可用
									if(!"1".equals(standardVO.getGood_state())){
										shelves = false;
										break breakfor;
									}
									//判断库存
									if(Integer.parseInt(standardVO.getNum())<Integer.parseInt(standardVO.getBuy_num())){
										stock = false;
										break breakfor;
									}
									
									//会员优惠
									if("1".equals(ticket_status)){
										//购买方式 现金61 提货券62 现金+提货券63
										if("61".equals(standardVO.getBuy_type())){
											order_good_price = Double.parseDouble(standardVO.getSell_price());
											order_good_ticket = 0;
										}
										else{
											order_good_price =  Double.parseDouble(standardVO.getTicket_price());
											order_good_ticket = Double.parseDouble(standardVO.getTicket());
										}
									}
									else{
										//现金
										if("61".equals(standardVO.getBuy_type())){
											order_good_price = Double.parseDouble(standardVO.getSell_price());
											order_good_ticket = 0;
										}
										else{
											order_good_price =  Double.parseDouble(standardVO.getSell_price())-memberCartServise.buySale(standardVO.getSell_price(), standardVO.getBuy_type(), standardVO.getTicket(), standardVO.getTicket_price(), member.getLevel(), ticket_rule, percent_rule, member_rate);
											order_good_ticket = 0;
										}
									}
									//会员折扣
									buy_sale = buy_sale +Integer.parseInt(standardVO.getBuy_num())*(memberCartServise.buySale(standardVO.getSell_price(), standardVO.getBuy_type(), standardVO.getTicket(), standardVO.getTicket_price(), member.getLevel(), ticket_rule, percent_rule, member_rate));
									
									//存OrderGood
									orderGood.setGood_id(standardVO.getGood_id());
									orderGood.setGood_standard_id(standardVO.getStandard_id());
									orderGood.setGood_name(standardVO.getGood_name());
									orderGood.setStandard_name(standardVO.getStandard_name());
									orderGood.setSell_price(String.valueOf(Double.parseDouble(standardVO.getSell_price())*Integer.parseInt(standardVO.getBuy_num())));
									orderGood.setImg(standardVO.getImg());
									orderGood.setNum(standardVO.getBuy_num());
									orderGood.setStandard_no(standardVO.getStandard_no());
									orderGood.setPrice(String.valueOf(order_good_price));
									orderGood.setTicket(String.valueOf(order_good_ticket));
									orderGood.setCompany_id(standardVO.getCompany_id());
									orderGood.setProGoodIdList(standardVO.getProGoodIdList());
									
									order_ticket = order_ticket + Integer.parseInt(standardVO.getBuy_num())*order_good_ticket;
									order_sell_price = order_sell_price + Double.parseDouble(standardVO.getSell_price())*Integer.parseInt(standardVO.getBuy_num());
									order_award_join = order_award_join + Double.parseDouble(standardVO.getAward_money()==null?"0":standardVO.getAward_money())*Integer.parseInt(standardVO.getBuy_num());
									orderGoodList.add(orderGood);
							 }
						 }
						 order.setOrderGoodList(orderGoodList);
						 //算折扣(整天JB算,也不知道在算啥)
						 order = calcuSales(order,member.getLevel());
						for (int j = 0; j < order.getOrderGoodList().size(); j++) {
							 if(Double.parseDouble(order.getOrderGoodList().get(j).getPrice())<0){
									order_price_state = false;
									break breakfor;
							 }
							 order_price = order_price + Integer.parseInt(order.getOrderGoodList().get(j).getNum())*Double.parseDouble(order.getOrderGoodList().get(j).getPrice());
						 }
						
						order_freight = calcuFreight(enterprise_id,order.getOrderGoodList(),addressVO.getAddress_id(),country);	 
						 //总价格
						 Total_Price = Total_Price + order_price;
						 //总运费
						 Total_Freight = Total_Freight + order_freight;
						 //总兑换券
						 Total_Ticket = Total_Ticket + order_ticket;
						 //存Order
						 if(order_price + order_freight==0){
								order_ticket_status = true;
						 }else{
								order_ticket_status = false;
						 }
						 SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
						 java.util.Date date=new java.util.Date(); 
						 //纯提货券订单
						 if(order_ticket_status){
							 order.setState("3");
							 order.setUse_ticket("Y");
							 order.setPay_time(sdf.format(date));
							 order.setPay_type("3");
							 order.setTotal_price("0");
							 order.setTotal_ticket(String.valueOf(order_ticket));
						 }
						 //不是纯提货券订单
						 else{
							 //使用提货券
							 if("1".equals(ticket_status)){
								 order.setState("2");
								 order.setUse_ticket("Y");
								 order.setTotal_price(String.valueOf(order_price));
								 order.setTotal_ticket(String.valueOf(order_ticket));
							 }
							 //未使用提货券
							 else{
								 order.setState("1");
								 order.setUse_ticket("N");
								 order.setTotal_price(String.valueOf(order_price));
								 order.setTotal_ticket("0");
							 }
						 }

						 order.setOrder_from(order_from);
						 order.setTotal_sell_price(String.valueOf(order_sell_price));
						 order.setTotal_buy_cash("0");
						 order.setCreate_by(member.getId());
						 order.setTicket_status(ticket_status);
						 order.setDelete_yn("N");
						 order.setAddress_tel(addressVO.getTel());
						 order.setAddress_name(addressVO.getName());
						 order.setAddress_content(addressVO.getCity()+" "+addressVO.getAddress());
						 order.setOrder_type("0");
						 order.setOrder_ticket_status(order_ticket_status);
						 //运费
						 order.setFreight(String.valueOf(order_freight));
						 order.setJoin_cash(String.valueOf(order_award_join));
						 order.setAddress_id(addressVO.getCity_id());
						 order.setEnterprise_id(enterprise_id);
						 order.setBuy_sale(String.valueOf(buy_sale));
						 order.setMember_rate(String.valueOf(member_rate));
						 order.setLevel_str(level_str);
						 order.setCountry(country);
						 order.setAddress_obj_en(addressVO.getAddress_obj_en());
						 orderList.add(order);
						 
					 }    // END breakfor
		
		
		if(order_price_state==false){
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("state", "10921");
				map.put("msg", "订单金额异常");
				map.put("result", "");
				map.put("remark", "");
				return map; 
		}
		 
		if("1".equals(ticket_status)){
			if(total_can_use_ticket<Total_Ticket){
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("state", "10902");
				map.put("msg", ticket_name+"不足");
				map.put("result", "");
				map.put("remark", "");
				return map; 
			}
		}
		if(shelves==false){
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("state", "10101");
			map.put("msg", "商品不可用");
			map.put("result", "");
			map.put("remark", "");
			return map; 
		}
		
		if(stock==false){
			
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("state", "10909");
			map.put("msg", "库存不足");
			map.put("result", "");
			map.put("remark", "");
			return map; 
		}
		
		for (int i = 0; i < standard_List.size(); i++) {
			int count = memberCartVOMapper.updStandardNum(standard_List.get(i).getStandard_id(),standard_List.get(i).getBuy_num());
			if(count==0){
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("state", "10909");
				map.put("msg", "库存不足");
				map.put("result", "");
				map.put("remark", "");
				return map; 
			}
		}
		
		//Insert  处理
		String order_pay_no = "";
		for (int i = 0; i < orderList.size(); i++) {
			memberCartVOMapper.InsertOrder(orderList.get(i));
			OrderVO order = orderList.get(i);
			if(i==0){
				order_pay_no =  order.getId();
			}else{
				order_pay_no = order_pay_no + ","+ order.getId();
			}
			OrderCaseVO orderCase = new OrderCaseVO();
			orderCase.setOrder_id(order.getId());
			orderCase.setCase_no("1");
			if(order.isOrder_ticket_status()){
				orderCase.setState("3");
			}else{
				orderCase.setState("1");
			}
			dao.insertOrderCase(orderCase);
			String case_id = orderCase.getId();
			List<OrderGoodVO> orderGoodList = orderList.get(i).getOrderGoodList();
			for (int j = 0; j < orderGoodList.size(); j++) {
				OrderGoodVO orderGood = orderGoodList.get(j);
				String order_id = order.getId();
				orderGood.setOrder_id(order_id);
				orderGood.setCase_id(case_id);
				String path = "Upload/order/"+order_id+"/";
				String file_name = "";
				 file_name  = OssUtil.copyFile(orderGood.getImg(),path);
				if("".equals(file_name)){
					throw new RuntimeException();
				}
				orderGood.setImg(file_name);
				dao.addOrderGood(orderGood);
				String order_good_id = orderGood.getId();
				for (int k = 0; k < orderGood.getProItemList().size(); k++) {
					String sale_id = orderGood.getProItemList().get(k).getPromotion_id();
					String sale_type = orderGood.getProItemList().get(k).getType();
					promotionVOMapper.addOrderDiscount(order_good_id,sale_id,sale_type);
				}
			}
			if(order.isOrder_ticket_status()==false){
				OrderTimer orderTime = new OrderTimer();
				orderTime.setOrder_id(order.getId());
				orderTime.setOpen_yn("Y");
				orderTime.setType("4");
				orderTime.setTime(pay_timer);
				orderTime.setCreate_time("");
				orderTime.setUpdate_time("");
				orderTime.setCase_id(case_id);
				memberCartVOMapper.addOrderTimer(orderTime);
				//延时队列 自动取消
				autoCancelOrder(order.getId(),orderTime.getId(),order.getTicket_status(),order.getPay_type(),order.getCreate_by(),pay_timer);
				
			}
			LogOrder log_ord = new LogOrder();
			log_ord.setOrder_id(order.getId());
			log_ord.setMember_id(member.getId());
			log_ord.setRemark("【订单】已生成");
			dao.InsertLogOrder(log_ord);
		} // 插入订单 end
		
		Map<String, Object> returnMap = new HashMap<String, Object>();
		returnMap.put("order_pay_no", order_pay_no);
		returnMap.put("free_balance", member.getFree_cash());
		returnMap.put("cash_balance", member.getGood_cash());
		returnMap.put("total_amount", String.valueOf(Total_Price+Total_Freight));
		returnMap.put("total_ticket", Total_Ticket);
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("state", "200");
		map.put("msg", "success");
		map.put("result", returnMap);
		map.put("remark", "");
		
		return map;
	}
	//算运费
	private double calcuFreight(String enterprise_id,List<OrderGoodVO> orderGoodList,String address_id,String country){
		double friehgt = 0;
		String standard_id= "";
		String standard_num = "";
		for (int i = 0; i < orderGoodList.size(); i++) {
			if(!orderGoodList.get(i).isFreight_state()){
				standard_id = standard_id + orderGoodList.get(i).getGood_standard_id() + "," ;
				standard_num = standard_num +  orderGoodList.get(i).getNum()+"," ;
			}
		}
		if("".equals(standard_id)){
			return 0;
		}else{
			if("0".equals(country)){
				standard_id = standard_id.substring(0,standard_id.length()-1);
				standard_num = standard_num.substring(0,standard_num.length()-1);
				if(standard_id!=null&&!"".equals(standard_id)&&standard_num!=null&&!"".equals(standard_num)){
					friehgt = goodTempService.calculateFeightEn(standard_id.split(","), standard_num.split(","), address_id);
				}
			}else{
				standard_id = standard_id.substring(0,standard_id.length()-1);
				standard_num = standard_num.substring(0,standard_num.length()-1);
				if(standard_id!=null&&!"".equals(standard_id)&&standard_num!=null&&!"".equals(standard_num)){
					friehgt = goodTempService.calculateFeight(standard_id.split(","), standard_num.split(","), address_id);
				}	
			}
			
			return friehgt;
		}
	}
	
	private void dealBenifit(Map map,String ticket_status,MemberVO member){
		Map order_map = (Map)map.get("result");
		String[] order_id_list =  order_map.get("order_pay_no").toString().split(",");
		for (int i = 0; i < order_id_list.length; i++) {
			OrderVO order = dao.getOrderById(order_id_list[i]);
			if("1".equals(ticket_status)){
				String total_ticket = dao.getTotalTicketByOrderId(order_id_list[i]);
				
				if(Integer.parseInt(total_ticket)>0){
					splitService.useTicketBuy(member.getId(), Integer.parseInt(total_ticket), order_id_list[i]);
				}
				
				if("1".equals(order.getTicket_status())&&"3".equals(order.getState())&&"3".equals(order.getPay_type())&&Double.parseDouble(order.getTotal_price())+Double.parseDouble(order.getFreight())==0){
					if(Double.parseDouble(order.getJoin_cash())>0){		
						try{
							splitService.splitJoinAward(member.getId(), member.getLevel(), 2, total_ticket,
									order.getMember_rate(), order_map.get("order_pay_no").toString(), order.getJoin_cash(), null);
						}catch(Exception e){
							e.printStackTrace();
						}
					}	
				}
			}
		}
	}

	public List<OrderVO> getSimpleOrderByIdList(String[] order_id_List) {
		return dao.getSimpleOrderByIdList(order_id_List);
	}

	public void updTest() {
		payService.updTest();
	}
	
	/**
	 * 计算折扣
	 * @param order
	 * @return
	 */
	public OrderVO calcuSales(OrderVO order,String member_level){
		List<PromotionGoodVO> actIds = new ArrayList<PromotionGoodVO>();
		List<String> typeOneAct = new ArrayList<String>();
		List<OrderGoodVO> orderGoodList = order.getOrderGoodList();
		for (int i = 0; i < orderGoodList.size(); i++) {
			actIds.addAll(orderGoodList.get(i).getProGoodIdList());
		}
		double act_sale = 0;
		for (int i = 0; i < actIds.size(); i++) {
			if("1".equals(actIds.get(i).getType())&&!typeOneAct.contains(actIds.get(i).getPromotion_id())){
				typeOneAct.add(actIds.get(i).getPromotion_id());
			}
		}
		//没有任何优惠活动
		if(actIds.size()==0){
			return order;
		}else{
				List<PromotionVO> proOneList = promotionVOMapper.getAllPromotionByProGoodId(typeOneAct,member_level);
				for (int i = 0; i < proOneList.size(); i++) {
					PromotionVO promotion = proOneList.get(i);
					int reach_count = 0;
					double reach_money = 0;  
					double total_price = 0;
					if(proOneList.get(i).getItemList().size()>0){
						List<String> goodIdList = new ArrayList<String>();
						for (int j = 0; j < orderGoodList.size(); j++) {
							boolean state = false;
							for (int k = 0; k < orderGoodList.get(j).getProGoodIdList().size(); k++) {
								if("1".equals(orderGoodList.get(j).getProGoodIdList().get(k).getType())&&orderGoodList.get(j).getProGoodIdList().get(k).getPromotion_id().equals(promotion.getPromotion_id())){
									state = true;
									goodIdList.add(orderGoodList.get(j).getGood_id());
								}
							}
							if(state){
								reach_count = reach_count + Integer.parseInt(orderGoodList.get(j).getNum());
								reach_money = reach_money + Double.parseDouble(orderGoodList.get(j).getSell_price());
								total_price = total_price + Integer.parseInt(orderGoodList.get(j).getNum())*Double.parseDouble(orderGoodList.get(j).getPrice());
							}
						}
						PromotionItemVO proItem = chooseCorrectSalesTypeOne(reach_count,reach_money,promotion);
						if(proItem.getId()!=null){
							double reduce_money = Double.parseDouble(proItem.getReduce_cash());
							act_sale = act_sale+reduce_money;
							for (int j = 0; j < orderGoodList.size(); j++) {
								boolean state = false;
								if(goodIdList.contains(orderGoodList.get(j).getGood_id())){
									state = true;
								}
								if(state){
									double price = Double.parseDouble(orderGoodList.get(j).getPrice());
									int num = Integer.parseInt(orderGoodList.get(j).getNum());
									orderGoodList.get(j).setPrice(String.valueOf((price*num-(price*num/total_price)*reduce_money)/num));
									orderGoodList.get(j).getProItemList().add(proItem);
									if("Y".equals(proItem.getPromotion_freight())){
										orderGoodList.get(j).setFreight_state(true);
									}
								}
							}
						}		
					}
				}
				order.setAct_sale(String.valueOf(act_sale));
				return order;
			}
		}	
	
	
	private PromotionItemVO chooseCorrectSalesTypeOne(int reach_count,double reach_money,PromotionVO proGood){
		String reach_type = proGood.getItemList().get(0).getType();
		List<PromotionItemVO> proItemList = proGood.getItemList();
		PromotionItemVO proItem = new PromotionItemVO();
		if(proItemList==null||proItemList.size()==0){
			return proItem;
		}
		for (int i = 0; i < proItemList.size(); i++) {
			
			String reach = proItemList.get(i).getReach();
			//满钱
			if("0".equals(reach_type)){
				if(Double.parseDouble(reach)>reach_money){
					proItemList.remove(i);
					i--;
				}
			}
			//满件
			else if("1".equals(reach_type)){
				if(Integer.parseInt(reach)>reach_count){
					proItemList.remove(i);
					i--;
				}
			}
		}
		if(proItemList==null||proItemList.size()==0){
			return proItem;
		}
		double suit_money = 0;
		int suit_count = 0;
		String pro_item_id="";

		for (int i = 0; i < proItemList.size(); i++) {
			String reach = proItemList.get(i).getReach();
			//满钱
			if("0".equals(reach_type)){
				if(Double.parseDouble(reach)>suit_money){
					suit_money = Double.parseDouble(reach);
					pro_item_id = proItemList.get(i).getId();
				}
			}
			//满件
			else if("1".equals(reach_type)){
				if(Integer.parseInt(reach)>suit_count){
					suit_count = Integer.parseInt(reach);
					pro_item_id = proItemList.get(i).getId();
				}
			}
		}
		
		for (int i = 0; i < proItemList.size(); i++) {
			if(proItemList.get(i).getId().equals(pro_item_id)){
				proItem = proItemList.get(i);
			}
		}	
		
		return  proItem;
	}
	
	//延时队列
	public void autoCancelOrder(String order_id,String order_timer_id,String ticket_status,String pay_type,String create_by,String pay_timer){
		
		DelayQueue<MessageUtil> queue = new DelayQueue<MessageUtil>();  
		long time = Long.parseLong(pay_timer.toString())*1000;
		MessageUtil m = new MessageUtil("pay_time", time);
		queue.offer(m);
		
		new Thread(new Runnable() {
			public void run() {
				try{
					MessageUtil take = queue.take();
					uorderService.UorderCalcelNoPay(order_id, order_timer_id, ticket_status, pay_type, create_by);
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		}).start();
	}
	
}
